﻿using Swashbuckle.Swagger;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Http.Description;

namespace SingleUserMall
{
    public class SwaggerFileUploadFilter : IOperationFilter
    {
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var parameters = apiDescription.ActionDescriptor.GetParameters();
            foreach (HttpParameterDescriptor parameterDesc in parameters)
            {
                var fileUploadAttr = parameterDesc.GetCustomAttributes<SwaggerFileUploadAttribute>().FirstOrDefault();
                if (fileUploadAttr != null)
                {
                    operation.consumes.Add("multipart/form-data");
                    var parame = operation.parameters.FirstOrDefault(x => x.name == parameterDesc.ParameterName);
                    if (parame == null)
                    {
                        operation.parameters.Add(new Parameter
                        {
                            name = parameterDesc.ParameterName,
                            @in = "formData",
                            description = "上传文件",
                            required = fileUploadAttr.Required,
                            type = "file"
                        });
                    }
                    else
                    {
                        parame.@in = "formData";
                        parame.description = "上传文件";
                        parame.required = fileUploadAttr.Required;
                        parame.type = "file";
                        parame.@default = null;
                    }
                }
            }
        }
    }
}
